import React, { useMemo, useState } from 'react';
import { View, Text, StyleSheet, Modal, TouchableOpacity, ScrollView } from 'react-native';

export type PriceRange = { min: number; max: number };
export type MileageRange = { min: number; max: number };

export type Filters = {
  brand?: string;
  price?: PriceRange;
  mileage?: MileageRange;
};

type Props = {
  visible: boolean;
  onClose: () => void;
  onApply: (f: Filters) => void;
};

const BRANDS = ['全部', '大众', '丰田', '本田', '比亚迪', '吉利', '特斯拉', '宝马', '奔驰'];
const PRICE_PRESETS: PriceRange[] = [
  { min: 0, max: 100000 },
  { min: 100000, max: 150000 },
  { min: 150000, max: 200000 },
  { min: 200000, max: 9999999 },
];
const MILEAGE_PRESETS: MileageRange[] = [
  { min: 0, max: 30000 },
  { min: 30000, max: 60000 },
  { min: 60000, max: 100000 },
  { min: 100000, max: 9999999 },
];

const FilterModal: React.FC<Props> = ({ visible, onClose, onApply }) => {
  const [brand, setBrand] = useState<string>('全部');
  const [price, setPrice] = useState<PriceRange | undefined>();
  const [mileage, setMileage] = useState<MileageRange | undefined>();

  const summary = useMemo(() => {
    const parts: string[] = [];
    if (brand && brand !== '全部') parts.push(brand);
    if (price) parts.push(`${Math.round(price.min / 10000)}-${Math.round(price.max / 10000)}万`);
    if (mileage) parts.push(`${Math.round(mileage.min / 10000)}-${Math.round(mileage.max / 10000)}万公里`);
    return parts.length ? parts.join(' · ') : '全部车辆';
  }, [brand, price, mileage]);

  const apply = () => onApply({ brand: brand === '全部' ? undefined : brand, price, mileage });

  return (
    <Modal visible={visible} animationType="slide" transparent>
      <View style={styles.mask}>
        <View style={styles.panel}>
          <ScrollView contentContainerStyle={{ padding: 16 }}>
            <Text style={styles.section}>品牌</Text>
            <View style={styles.rowWrap}>
              {BRANDS.map((b) => (
                <TouchableOpacity key={b} style={[styles.tag, brand === b && styles.tagActive]} onPress={() => setBrand(b)}>
                  <Text style={[styles.tagText, brand === b && styles.tagTextActive]}>{b}</Text>
                </TouchableOpacity>
              ))}
            </View>

            <Text style={styles.section}>价格</Text>
            <View style={styles.rowWrap}>
              {PRICE_PRESETS.map((p, i) => (
                <TouchableOpacity key={i} style={[styles.tag, price === p && styles.tagActive]} onPress={() => setPrice(p)}>
                  <Text style={[styles.tagText, price === p && styles.tagTextActive]}>
                    {Math.round(p.min / 10000)}-{Math.round(p.max / 10000)}万
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <Text style={styles.section}>里程</Text>
            <View style={styles.rowWrap}>
              {MILEAGE_PRESETS.map((m, i) => (
                <TouchableOpacity key={i} style={[styles.tag, mileage === m && styles.tagActive]} onPress={() => setMileage(m)}>
                  <Text style={[styles.tagText, mileage === m && styles.tagTextActive]}>
                    {Math.round(m.min / 1000)}-{Math.round(m.max / 1000)}千公里
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>

          <View style={styles.footer}>
            <TouchableOpacity style={styles.btnGhost} onPress={onClose}>
              <Text style={styles.btnGhostText}>取消</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.btn} onPress={apply}>
              <Text style={styles.btnText}>应用</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  mask: { flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'flex-end' },
  panel: { maxHeight: '80%', backgroundColor: '#fff', borderTopLeftRadius: 16, borderTopRightRadius: 16 },
  section: { fontSize: 14, color: '#333', marginTop: 12, marginBottom: 8, fontWeight: '600' },
  rowWrap: { flexDirection: 'row', flexWrap: 'wrap' },
  tag: { paddingHorizontal: 12, paddingVertical: 8, borderRadius: 16, backgroundColor: '#F3F4F6', marginRight: 8, marginBottom: 8 },
  tagActive: { backgroundColor: '#007AFF22' },
  tagText: { color: '#333' },
  tagTextActive: { color: '#007AFF', fontWeight: '600' },
  footer: { flexDirection: 'row', justifyContent: 'space-between', padding: 16, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: '#eee' },
  btn: { backgroundColor: '#007AFF', borderRadius: 8, paddingHorizontal: 20, paddingVertical: 10 },
  btnText: { color: '#fff', fontWeight: '600' },
  btnGhost: { paddingHorizontal: 20, paddingVertical: 10 },
  btnGhostText: { color: '#666' },
});

export default FilterModal;

